const Koa = require('koa')
const ejs=require('ejs');
const path=require('path')
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
// let Koa = require("koa2");
const WebSocket = require("koa-websocket");
const route = require('koa-route')
const nssd = require('./controller/nssd')

/* 实例化 WebSocket, 实例化储存所有上线文数组 并分配监听的端口 */
const app = WebSocket(new Koa());

const index = require('./routes/index')

// const app = new Koa()
// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  formLimit: '10mb',
  enableTypes:['json', 'form', 'text']
}))
app.use(json({pretty:false}))
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'));


// Using route
app.ws.use(route.all('/websocket',nssd.websocket));
app.listen(3001);

// 配置服务端模板渲染引擎中间件
app.use(views(path.join(__dirname, './views'), {
  extension: 'ejs'
}))

// app.use(views(__dirname + '/views', {
//   extension: 'pug'
// }))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
